/**
 * 封装请求request
 * @param { 接口地址 } url
 * @param { 接口传递参数 } data
 * @param { 请求头 } header
 * @param { 上传文件路径 } filePath
 * @param { 上传文件对应的key } name
 */
 //  finally

const $tap = require('./../common/tap.js')

const BETAURL = 'https://glapi.bempty.cn';

// 请求status出错时
let httpErr = (resolve, reject, res, url) => {
	if(res.status === 401) {
		$tap.showToast('请登录');
		setTimeout(() => {
			wx.reLaunch({
				url: '/pages/login/login'
			})
		}, 1500)
	}
    if(res.code === 1) {
        if(res.data && typeof res.data.total === 'number' && res.data.total <= 0 && url != '/api-h/articleComments/comments-anon/external/findArticleCommentInfos') {
            $tap.showToast('暂无数据');
            wx.stopPullDownRefresh();
        } else {
            resolve(res)
        }
    } else {
        $tap.showToast(res.msg);
    }
}

 // get请求
let get = (url, data, header = {}) => {
    if(wx.getStorageSync('token')) {
        header['Authorization'] = wx.getStorageSync('token');
    }
    return new Promise((resolve, reject) => {
        wx.request({
            url: BETAURL + url,
            data: data,
            method: 'GET',
            header: header,
            success: (res) => {
                httpErr(resolve, reject, res.data, url);
            },
            fail: err => {
                reject(err)
            }
        })
    })
}

// post请求
let post = (url, data, header = {}) => {
    if(!header['Content-Type']) {
        header['Content-Type'] = 'application/x-www-form-urlencoded'
    }
    if(wx.getStorageSync('token')) {
        header['Authorization'] = wx.getStorageSync('token');
    }
    return new Promise((resolve, reject) => {
        wx.request({
            url: BETAURL + url,
            data: data,
            method: 'POST',
            header: header,
            success: res => {
                httpErr(resolve, reject, res.data);
            },
            fail: err => {
                reject(err)
            }
        })
    })
}

// put请求
let put = (url, data, header = HEARD) => {
    if(!header['Content-Type']) {
        header['Content-Type'] = 'application/x-www-form-urlencoded'
    }
    return new Promise((resolve, reject) => {
        wx.request({
            url: BETAURL + url,
            data: data,
            method: 'PUT',
            header: header,
            success: res => {
                httpErr(resolve, reject, res.data);
            },
            fail: err => {
                reject(err)
            }
        })
    })
}

// 上传图片
let upload = (url, filePath, name = 'file', header) => {
    return new Promise((resolve, reject) => {
        wx.chooseImage({
            url: BETAURL + url,
            filePath: filePath,
            name: name,
            header: header,
            success: res => {
                resolve(res)
            },
            fail: err => {
                reject(err)
            }
        })
    })
}

module.exports = {
    get,
    post,
    put,
    upload
}